#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
    vector<vector<int>> permuteUnique(vector<int>& nums) {
        vector<bool>uesd(nums.size(), false);
        vector<vector<int>> result;
        vector<int> path;
        vector<vector<int>> samed;
        dfs(nums, uesd, result, path, samed);
        return result;
    }
private:
    void dfs(vector<int>& nums, vector<bool>& uesd, vector<vector<int>>& result, vector<int>& path, vector<vector<int>>& samed) {
        if (nums.size() == path.size()) {
            for (int i = 0; i < samed.size(); i++) {
                if (samed[i] == path) { return; }
            }
            result.push_back(path);
            samed.push_back(path);
            return;
        }
        for (int i = 0; i < nums.size(); i++) {
            if (uesd[i]) { continue; }
            path.push_back(nums[i]);
            uesd[i] = true;
            dfs(nums, uesd, result, path, samed);
            path.pop_back();
            uesd[i] = false;
        }
    }
};
class Solution {
public:
    vector<vector<int>> permuteUnique(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        vector<bool>uesd(nums.size(), false);
        vector<vector<int>> result;
        vector<int> path;
        dfs(nums, uesd, result, path);
        return result;
    }
private:
    void dfs(vector<int>& nums, vector<bool>& uesd, vector<vector<int>>& result, vector<int>& path) {
        if (nums.size() == path.size()) {
            result.push_back(path);
            return;
        }
        for (int i = 0; i < nums.size(); i++) {
            if (uesd[i]) { continue; }
            if (i > 0 && nums[i] == nums[i - 1] && !uesd[i - 1])continue;
            path.push_back(nums[i]);
            uesd[i] = true;
            dfs(nums, uesd, result, path);
            path.pop_back();
            uesd[i] = false;
        }
    }
};